package com.example.black.myapplication.myhandler;

public class MyLooper {
    static ThreadLocal<MyLooper> sThreadLocal = new ThreadLocal<>();
    MyMessageQueue myMessageQueue;
    Thread thread;
    private MyLooper() {
        myMessageQueue = new MyMessageQueue();
        thread = Thread.currentThread();
    }
    public static void perpareMainLooper(){
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        prepare();
    }
    public static void prepare(){
        sThreadLocal.set(new MyLooper());
    }

    public static void loop(){
        MyLooper myLooper = getMyLooper();
        final MyMessageQueue messageQueue = myLooper.myMessageQueue;
        for (;;){
           MyMessage myMessage = messageQueue.next();
           if (myMessage == null){
               return;
           }
           myMessage.target.dispatchMessage(myMessage);
         //   System.out.println("myLooper dispatchMessage"+myMessage.obj.toString());
           myMessage.recycle();
        }

    }

    public static MyLooper getMyLooper(){
        return sThreadLocal.get();
    }
}
